<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 系统角色 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <el-form :inline="true" class="demo-form-inline">
                <el-form-item>
                    <el-input v-model="query.name" @keyup.enter.native="handleSearch" placeholder="角色名"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input style="display: none"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
                    <el-button type="primary" icon="el-icon-plus" @click="handleEdit()">新增</el-button>
                </el-form-item>
            </el-form>

            <el-table
                v-loading="loading"
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                row-key="id"
            >
                @selection-change="handleSelectionChange" >
                <el-table-column class-name="role2" prop="name" label="角色名"></el-table-column>
                <el-table-column prop="remark" label="备注信息"></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template v-if="!scope.row.isStatic" slot-scope="scope">
                        <!-- v-if="scope.row.isSuper!='Administrator'" -->
                        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>

                        <!-- <el-button type="text" icon="el-icon-edit"  @click="$router.push({path:'/role/edit',query:{id: scope.row.id}});">编辑</el-button> -->

                        <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    @size-change="handleSizeChange"
                    background
                    @current-change="handleCurrentChange"
                    :current-page="1"
                    :page-sizes="[10, 15, 20, 30]"
                    :page-size="10"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pageTotal"
                >
                </el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog :close-on-click-modal="false" title="编辑内容" :visible.sync="editVisible">
            <el-row type="flex">
                <el-col :span="16" :offset="4" justify="center">
                    <el-form ref="form" :model="form" label-width="auto" :rules="rulesForm">
                        <el-form-item label="角色名称" prop="name">
                            <el-input v-model="form.name" id="name"></el-input>
                        </el-form-item>

                        <el-form-item label="备注信息" prop="remark">
                            <el-input id="remark" type="textarea" :rows="3" placeholder="不超过50个字" v-model="form.remark"></el-input>
                        </el-form-item>

                        <el-form-item label="权限配置">
                            <el-tree
                                ref="tree"
                                :data="allPermission"
                                show-checkbox
                                :default-expanded-keys="expandedkeys"
                                :default-checked-keys="checkedKeys"
                                node-key="id"
                                default-expand-all
                                :props="defaultProps"
                            >
                            </el-tree>
                        </el-form-item>

                        <el-form-item justify="center">
                            <el-button type="primary" @click="saveEdit('form')">保存</el-button>
                            <el-button @click="resetForm('form')">取消</el-button>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios';
export default {
    name: 'role_list',
    data() {
        return {
            query: {
                name: '',
                pageIndex: 1,
                pageSize: 10
            },
            tenantId: '',
            tableData: [],
            editVisible: false,
            pageTotal: 0,
            form: {},

            loading: false,
            allPermission: [],
            checkedKeys: [],
            expandedkeys: [],
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            rulesForm: {
                name: [
                    {
                        required: true,
                        message: '请输入角色名称!'
                    },
                    {
                        min: 2,
                        max: 30,
                        message: '长度在 2 到 10 个字符'
                    }
                ],
                remark: [
                    {
                        min: 0,
                        max: 50,
                        message: '长度不能超过50个字符'
                    }
                ]
            }
        };
    },
    created() {
        this.loading = true;

        this.getData();

        //获取当前角色的全部权限--5f4794f8b59cf7506f5d3197
        //获取当前用户的可配置权限
        axios.get(config.gatewayUrl + '/api/identity/menu').then((res) => {
            var allP = [];

            var fisrtMenu = res.data.items.filter(function (item) {
                return item.name == 'YydPc';
            })[0];

            for (let index = 0; index < fisrtMenu.items.length; index++) {
                const first = {
                    id: fisrtMenu.items[index].name,
                    label: fisrtMenu.items[index].displayName,
                    children: []
                };

                this.expandedkeys.push(fisrtMenu.items[index].name);
                //二级菜单
                var second = fisrtMenu.items[index].items;

                for (let j = 0; j < second.length; j++) {
                    first.children.push({
                        id: second[j].name,
                        label: second[j].displayName,
                        children: []
                    });
                    //三级功能按钮
                    var third = second[j].items;
                    for (let k = 0; k < third.length; k++) {
                        first.children[j].children.push({
                            id: third[k].name,
                            label: third[k].displayName
                        });
                    }
                }
                allP.push(first);
            }
            this.allPermission = allP;
        });
    },
    mounted() {},
    methods: {
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.getData();
        },
        getData() {
            this.loading = true;
            axios
                .post(config.gatewayUrl + '/api/identity/yyd-roles/getpagelist', {
                    name: this.query.name,
                    skipCount: this.query.pageIndex,
                    maxResultCount: this.query.pageSize
                })
                //成功返回
                .then((res) => {
                    this.tableData = res.data.items;
                    this.pageTotal = res.data.totalCount;
                    this.loading = false;
                })
                //失败返回
                .catch((error) => {
                    console.log(error);
                });
        },

        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            var that = this;
            this.$confirm('确定要删除【' + row.name + '】吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    axios.delete(config.gatewayUrl + '/api/identity/yyd-roles/' + row.id).then((res) => {
                        that.getData();
                        that.tableData.splice(index, 1);
                        that.$message.success('删除成功');
                    });
                })
                .catch(() => {});
        },

        // 编辑操作
        handleEdit(index, row) {
            this.checkedKeys = [];
            if (row) {
                this.idx = index;
                this.form = row;
                var d = this.form.name;

                axios.get(config.gatewayUrl + '/api/identity/permissions?providerName=R&providerKey=' + d).then((res) => {
                    for (let i = 0; i < res.data.items.length; i++) {
                        this.$refs.tree.setChecked(res.data.items[i].name, true, false);
                        //array.push(res.data.permissionsList[i].name);
                    }
                    //this.checkedKeys =array;
                    //this.$refs.tree.setCheckedKeys(array);
                });
            } else {
                this.form = {
                    id: null,
                    name: '',
                    remark: ''
                };
            }
            this.editVisible = true;
        },
        // 保存编辑
        saveEdit(formName) {
            var that = this;

            this.$refs[formName].validate((valid) => {
                if (valid) {
                    var dto = {
                        name: this.form.name,
                        id: this.form.id,
                        remark: this.form.remark
                    };
                    var PermissionsList = [];
                    var selectedTreeArray = [];
                    var hf = this.$refs.tree.getHalfCheckedKeys();
                    var allh = this.$refs.tree.getCheckedKeys();
                    if (hf.length == 0 && allh.length == 0) {
                        this.$message.error('请勾选角色的权限！');
                        return;
                    }
                    selectedTreeArray = selectedTreeArray.concat(hf).concat(allh);
                    for (let i = 0; i < selectedTreeArray.length; i++) {
                        PermissionsList.push(selectedTreeArray[i]);
                    }

                    dto.permissionGrants = PermissionsList;
                    axios
                        .post(config.gatewayUrl + '/api/identity/yyd-roles', dto)
                        .then((res) => {
                            that.editVisible = false;
                          
                            that.$message.success(`保存成功!`);
                            that.getData();
                        })
                        .catch((error) => {
                      
                            console.log(error); //  错误处理 相当于error
                        })
                        .finally((res) => {
                        
                        });
                } else {
                    return false;
                }
            });
        },
        resetForm(formName) {
            var that = this;
            this.$refs.tree.setCheckedKeys([]);
            this.form = {
                id: '',
                name: '',
                description: '',
                tenantId: ''
            };

            setTimeout(function () {
                that.$refs.form.clearValidate();
            }, 100);

            this.editVisible = false;
        },
        // 分页导航
        handlePageChange(val) {
            //this.$set(this.query, 'pageIndex', val);

            this.query.pageIndex = val;
            this.getData();
        },
        handleSizeChange(val) {
            this.query.pageIndex = val;
            this.getData();
        },
        handleCurrentChange(val) {
            this.query.pageIndex = val;

            this.getData();
        }
    },
    watch: {}
};
</script>

<style scoped>
</style>
